<?php
    class option_model extends Model
    {
        public function __construct(){
            parent::__construct();
            $this->setTableName('options');
        }
        
        public function get($optionName){
        	if (empty($optionName))
        		return null;
        	
    		$sql = 'select value from ' . $this->getTableName() 
            	. ' where name = {0} limit 1';
    		$val = $this->db->fetchOne($sql, array($optionName));
    		
    		return empty($val) ? null : $val['value'];
        }
        
        public function set($optionName, $val){
        	if (empty($val))
        		return false;
        		
        	$sql = null;
        	
        	//loading user model fetching current user id, if null return false
        	$userId = $this->load->model('user')->getUserId();
        	
        	$userId = intval($userId);
        	
        	if (empty($userId)){
        		return null;
        	}
        	
            $optionInfo = $this->get($optionName);
     		if (empty($optionInfo)){
     			//record not exist
     			$sql = 'insert into ' . $this->getTableName()
     				 . ' (creator_user_id, name, value) values({0}, {1}, {2})';
     		}
     		else{
     			//record exist update
     			$sql = 'update ' . $this->getTableName()
     				 . ' set creator_user_id = {0}, name = {1}, value = {2} limit 1';
     		}
     		
     		return $this->db->query($sql, array($userId, $optionName, $val));
        }
    }